<template>
	<view class="order">
		<!-- 轮播 -->
		<view class="banner-list">
			<u-swiper :list="bannerList" keyName="image_text" @click="bannerBtn" autoplay :interval="5000" circular
				imgMode="aspectFill" height="400rpx" radius="0"></u-swiper>
		</view>

		<!-- 通用左右边距框架 -->
		<view class="mx-20">
			<!-- nav菜单 -->
			<view class="overflow-x-scroll flex justify-around bg-info-1 p-20 rd-16 shadow-s fs-24 px-20 mb-20 text-center text-nowrap relative">
				<view class="inline-block mb-20">
					<image class="w-90 h-90" src="https://number-baby.oss-cn-beijing.aliyuncs.com/uploads/20251112/fddd3c1982dcb3e016d697bd99279915.png" @click="goPath('/pages/home/zhaoshang')"></image>
					<view>招商合作</view>
				</view>
				<view class="inline-block mb-20">
					<image class="w-90 h-90" src="https://number-baby.oss-cn-beijing.aliyuncs.com/uploads/20251112/bb9e16017146752ffe0b92a01a2f99eb.png" @click="goPath('/pages/order/text-list?m_type=3')"></image>
					<view>推广必读</view>
				</view>
				
				<view class="inline-block mb-20">
					<image class="w-90 h-90" src="https://number-baby.oss-cn-beijing.aliyuncs.com/uploads/20251112/0d414dc196abdc0926a19116952250d3.png" @click="goPath('/pages/order/text-list?m_type=3')"></image>
					<view>一键通查</view>
				</view>
				<view class="inline-block mb-20">
					<image class="w-90 h-90" src="https://number-baby.oss-cn-beijing.aliyuncs.com/uploads/20251112/86ff8421c354a48bea4210fab180e038.png" @click="showPoster = true"></image>
					<view>店铺分享</view>
				</view>
			</view>
			
			<!-- 店铺信息 -->
			<view class="my-20 bg-fff rd-16 overflow-hidden shadow-s">
				<view class="flex-between-center p-20">
					<view class="flex-y-center">
						<view class="w-100 h-100 bg-primary rd-8"></view>
						<view class="ml-10">
							<view class="flex-y-center c-333 fs-30 mb-10">{{storeinfo.name}} <span class="c-fff rd-6 fs-22 bg-info-12 px-10 py-4 ml-10">{{storeinfo.tag}}</span></view>
							<view class="flex-y-center c-999">
								已购{{storeinfo.sailnum}}件
								<u-rate count="5" active-color="#FBD068" inactive-color="#FBD068" :value="storeinfo.rate" allowHalf readonly></u-rate>
							</view>
						</view>
					</view>
					<view>
						<view class="flex-y-center c-666 fs-22" @click="openAreaSelect">
							<text class="siconfont icon-dingwei fs-52 pr-10 color-primary"></text>
							<view class="text-center">
								<view>{{addressInfo.area}}</view>
								<view>{{addressInfo.region}}</view>
							</view>
						</view>
					</view>
				</view>
				
				<view class="bg-primary-2 flex-between-center p-20">
					<view class="fs-30 fw-600 c-666">店铺保障</view>
					<view class="color-primary fs-22">官方正品·免费领用·包邮到家</view>
				</view>
				
			</view>

			<!-- 公告 -->
			<view class="shadow-s rd-16 my-20 bg-info-1 overflow-hidden">
				<u-notice-bar @click="showSystemContent=true" :text="systemContentdata.title" bgColor="#fff"></u-notice-bar>
				<!-- 封装的弹窗，content为内容，title为标题（标题可不传）close为监听动作，可以直接使用方法或设置弹窗属性关闭 -->
				<Popup :content="systemContentdata.content" :title="systemContentdata.title" :show="showSystemContent" @close="showSystemContent=false"/>
			</view>
					

			<view class="search_box">
				<u-tabs :list="goodscategory" :current="catecurrent" @click="cateChange">
					<view slot="right" class="pl-8" @tap="bigsearch=true">
						<view class="flex-y-center"><text class="siconfont icon-shaixuan pr-10"></text>筛选</view>
					</view>
				</u-tabs>				
			</view>
			
			
			<!-- 号卡商品列表 -->
			<view class="pdlist">
				<!-- 组装成组件，通过searchform传入搜索条件进行搜索 -->
				<userGoods ref="user_goods" v-model="searchform"></userGoods>
			</view>
			<!-- 号卡商品列表结束 -->
			

		</view>
		
		<!-- 各种弹窗及弹出层 -->
		<u-popup :show="bigsearch" @close="bigsearch=false" mode="right">
				<view class="w-70vw p-20 pl-40">
					<view class="fs-30 fw-600">筛选条件</view>
					
					<!-- <view class="my-20">
						<view class="mb-10">排序方式</view>
						<view class="flex-between-center rd-16 bg-info-3 h-60 p-20">
							<view class="c-999">请选择排序方式</view>
							<text class="siconfont icon-xiangyou1 c-999 rotate-90"></text>
						</view>
					</view> -->
									
									
					<view class="my-20">
						<view class="mb-10">商品名称</view>
						<u--input
							class="bg-info-3 h-60 p-20"
							placeholder="请输入商品名称"
							border="surround"
							v-model="searchform.key"
						></u--input>
					</view>
					
					<view class="my-20">
						<view class="mb-10">运营商</view>
						<view class="flex-between-center rd-16 bg-info-3 h-60 p-20" 
						      @click="openPicker('运营商', pdsearchdata.operator_arr, 'operator')">
							<view :class="searchform.operator?'c-333':'c-999'">
								{{ searchform.operator ? getLabelByValue(pdsearchdata.operator_arr, searchform.operator) : '请选择运营商' }}
							</view>
							<text class="siconfont icon-xiangyou1 c-999 rotate-90"></text>
						</view>
					</view>
					
					<view class="my-20">
						<view class="mb-10">结算模式</view>
						<view class="flex-between-center rd-16 bg-info-3 h-60 p-20" 
						      @click="openPicker('结算模式', pdsearchdata.jiesuan_time_arr, 'jiesuan_time')">
							<view :class="searchform.jiesuan_time?'c-333':'c-999'">
								{{searchform.jiesuan_time ? getLabelByValue(pdsearchdata.jiesuan_time_arr, searchform.jiesuan_time)  : '请选择结算模式'}}  
							</view>
							<text class="siconfont icon-xiangyou1 c-999 rotate-90"></text>
						</view>
					</view>
					
					<view class="my-20">
						<view class="mb-10">归属地</view>
						<view class="flex-between-center rd-16 bg-info-3 h-60 p-20" 
						      @click="openPicker('归属地', pdsearchdata.gushudi_type, 'gushudi_key')">
							<view :class="searchform.gushudi_key?'c-333':'c-999'">
								{{searchform.gushudi_key ? getLabelByValue(pdsearchdata.gushudi_type, searchform.gushudi_key) : '请选择结算模式'}}
							</view>
							<text class="siconfont icon-xiangyou1 c-999 rotate-90"></text>
						</view>
					</view>
					
					<view class="my-20">
						<view class="mb-10">收货地</view>
						<u--input
							class="bg-info-3 h-60 p-20"
							placeholder="请输入省或市"
							border="surround"
							v-model="searchform.shouhuo_key"
						></u--input>
					</view>
					
					<!-- 弹窗形式暂时保留 -->
					<!-- <view class="my-20">
						<view class="mb-10">首充金额</view>
						<view class="flex-between-center rd-16 bg-info-3 h-60 p-20" 
						      @click="openPicker('首充金额', pdsearchdata.recharge_requirement_arr, 'recharge_requirement')">
							<view :class="searchform.recharge_requirement?'c-333':'c-999'">
								{{ searchform.recharge_requirement ? searchform.recharge_requirement : '请选择首充金额' }}
							</view>
							<text class="siconfont icon-xiangyou1 c-999 rotate-90"></text>
						</view>
					</view> -->
					
					<!-- 点选形式 -->
					<view class="my-20">
						<view class="mb-10">首充金额</view>
						 <view 
							v-for="(item, index) in rechargeOptions" 
							:key="index"
							class="inline-block rd-8 p-20 mb-10 mx-4"
							:class="searchform.recharge_requirement === item.value ? 'bg-primary c-fff' : 'bg-info-3'"
							@click="selectRecharge(item.value)"
						>
							{{ item.label>0?item.label+'元':'无需充值' }}
						</view>
					</view>
					
					
					
					<view class="my-20">
						<view class="mb-10">可否在线选号</view>
						<view class="flex-between-center rd-16 bg-info-3 h-60 p-20" 
						      @click="openPicker('选号类型', pdsearchdata.is_selection_arr, 'is_selection')">
							<view :class="searchform.is_selection?'c-333':'c-999'">
								{{ searchform.is_selection ? getLabelByValue(pdsearchdata.is_selection_arr, searchform.is_selection) : '请选择选号类型' }}
							</view>
							<text class="siconfont icon-xiangyou1 c-999 rotate-90"></text>
						</view>
					</view>
					
					<view class="my-20">
						<view class="mb-10">下单年龄</view>
						<view class="flex-between-center">
							<u--input
								class="bg-info-3 h-60 p-20 mr-10"
								placeholder="请输入最低年龄"
								border="surround"
								v-model="searchform.age_min"
								type="number"
							></u--input>
							<u--input
								class="bg-info-3 h-60 p-20 ml-10"
								placeholder="请输入最高年龄"
								border="surround"
								v-model="searchform.age_max"
								type="number"
							></u--input>
						</view>
					</view>
					<view class="mt-80 flex-around-center text-center">						
						<view class="bg-info-4 rd-8 w-100v p-20 mr-10" @click="resetFilter">重置</view>
						<view class="bg-primary rd-8 c-fff w-100v p-20 ml-10" @click="submitFilter">提交</view>
					</view>				
				</view>
				
				<!-- 选择器弹窗 -->
				<u-picker 
					:show="showPicker" 
					:columns="pickerColumns" 
					keyName="key"
					:defaultIndex="pickerDefaultIndex"
					@confirm="handlePickerConfirm" 
					@cancel="showPicker = false"
					:closeOnClickOverlay="true"
				></u-picker>
				
		</u-popup>
		<!-- 条件筛选结束 -->
		
		
		
		<!-- 选择省市区 -->
		<AddressSelect ref="cityPickerRef"
			:api-param="addressInfo"
			@confirm="handleConfirm"
		></AddressSelect>
		
		<!-- 海报生成 -->
		<CreatePoster
		      :show="showPoster"
		      :qrcode="qrcodeUrl"
		      :backgroundList="bgList"
		      @update:show="showPoster = $event"
		    />
		
		<page-footer v-model="navigationList"></page-footer>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import ConfirmReceipt from '@/components/confirm_receipt/confirm_receipt.vue';
	import AddressSelect from "@/components/addressSelect.vue"
	import pageFooter from "@/components/pageFooter";
	import userGoods from '@/components/goods/user_goods.vue';

	export default {
		components: {
			ConfirmReceipt,
			pageFooter,
			AddressSelect,
			userGoods
		},
		data() {
			return {
				bigsearch: false,
				showPicker: false,
				// Picker相关状态
				pickerColumns: [],
				pickerDefaultIndex: [0],
				currentPickerTitle: '',
				currentPickerOptions: [],
				currentPickerField: '',
				
				showrules: true,		
				show: true,
				bannerList: [],
				status: 'loadmore',
				navigationList: [{
						"name": "首页",
						"link": "/pages/home/home",
						"icon": "home-fill"
					},
					{
						"name": "推广",
						"link": "/pages/shop/inv_records",
						"icon": "share-fill"
					},
					{
						"name": "客服",
						"link": "/pages/my/kefu",
						"icon": "weixin-fill"
					},
					{
						"name": "我的",
						"link": "/pages/my/index",
						"icon": "account-fill"
					}
				],
				storeinfo: {
					name: '流量卡店铺',
					tag: '金牌店铺',
					sailnum: 2051,
					rate: 3.5
				},
				systemContentdata: { title: '', content: '' },
				showSystemContent: false,
				goodscategory: [],
				catecurrent: 0,
				productListdata: [],
				addressInfo: {
					province: "北京",
					province_id: '',
					area: "北京市",
					area_id: '',
					region: "东城区",
					region_id: '',
				},
				searchform: {
					page: 1,
					is_remove: 1,
					is_commission: 1,
					province_id: '',
					city_id: '',
					region_id: '',
					key: '',
					jiesuan_time: '',
					gushudi_key: '',
					shouhuo_key: '',
					recharge_requirement: '',
					is_selection: '',
					age_min: '',
					age_max: '',
					sort: '',
					category_id: ''
				},
				sortdata: [],
				pdsearchdata: {},
				currentValue: '',
				ids: '',
				isLocationReady: false ,// 新增：标记定位是否完成
				rechargeOptions:[],//首充金额使用点选形式展示
				showPoster: false,
				  qrcodeUrl: 'https://number-baby.oss-cn-beijing.aliyuncs.com/uploads/20251112/86ff8421c354a48bea4210fab180e038.png',
				  bgList: [
					'https://number-baby.oss-cn-beijing.aliyuncs.com/uploads/20251112/813f5d7f832298d5d6430d9171b417c7.jpg',
					'http://yuechonglm.oss-cn-shenzhen.aliyuncs.com/6722ded5d0181.jpg',
				  ],
			};
		},
		computed: {
			...mapState({
				userinfo: state => state.userinfo
			}),
		},
		onLoad(opt) {
			this.searchform.page = 1
			this.ids = opt.ids || '';
			
			// 初始化数据
			this.initData();
		},
		onShow() {
			// 如果定位已完成，重新加载商品列表
			if (this.isLocationReady) {
				this.refreshGoodsList();
			}
		},
		
		methods: {
			onPosterClose() {
			      console.log('海报弹窗关闭');
			    },
			// 初始化数据
			async initData() {
				try {
					// 并行加载初始数据
					await Promise.all([
						this.getBanners(),
						this.popDictionary(),
						this.systemContent(),
						this.getCateList(),
						this.shopInfo(),
						this.productSearch()
					]);
					
					// 最后获取定位
					await this.selfLocation();
				} catch (error) {
					console.error('初始化数据失败:', error);
					this.$tips.toast('数据加载失败，请重试');
				}
			},
			
			// 工具函数：对象转下拉选项数组
			convertObjToOptions(obj) {
				if (!obj || typeof obj !== 'object') return [];
				return Object.entries(obj).map(([value, label]) => ({
					value: value,
					label: label.toString()
				}));
			},

			// 打开下拉选择
			openPicker(title, optionObj, field) {
				if (!optionObj) {
					this.$tips.toast('选项数据加载中，请稍后');
					return;
				}
				
				this.currentPickerTitle = title;
				this.currentPickerOptions = this.convertObjToOptions(optionObj);
				console.log("this.currentPickerOptions::::",this.currentPickerOptions);
				this.currentPickerField = field;
				
				// 设置picker列数据
				this.pickerColumns = [this.currentPickerOptions.map(item => item.label)];
				
				// 设置默认选中项
				const selectedValue = this.searchform[field] || '';
				const selectedIndex = this.currentPickerOptions.findIndex(
					item => item.value === selectedValue
				);
				this.pickerDefaultIndex = [selectedIndex > -1 ? selectedIndex : 0];
				
				this.showPicker = true;
			},

			// 选择确认
			handlePickerConfirm(e) {
				console.log('picker确认事件:', e);
				console.log('value:', e.value); // 显示的文字数组
				console.log('index:', e.indexs); // 选中的索引
				console.log('选项数组:', this.currentPickerOptions);
				
				const { indexs } = e;
				if (indexs && indexs[0] !== undefined) {
					const selectedItem = this.currentPickerOptions[indexs[0]];
					console.log('选中项:', selectedItem);
					
					if (selectedItem) {
						this.searchform[this.currentPickerField] = selectedItem.value;
					}
				}
				
				this.showPicker = false;
			},

			// 提交筛选
			submitFilter() {
				// 验证年龄范围
				if (this.searchform.age_min && this.searchform.age_max) {
					const min = parseInt(this.searchform.age_min);
					const max = parseInt(this.searchform.age_max);
					if (min > max) {
						this.$tips.toast('最低年龄不能大于最高年龄');
						return;
					}
				}
				
				this.searchform.page = 1;
				this.refreshGoodsList();
				this.bigsearch = false;
			},
			getLabelByValue(obj, value) {
				console.log("obj:::::",obj);
				console.log("value::::",value);
				if (!obj || !value) return '';
				return obj[value] || '';
			},

			// 重置筛选条件
			resetFilter() {
				// 保存位置相关参数
				const { province_id, city_id, region_id, is_remove, is_commission } = this.searchform;
				
				this.searchform = {
					page: 1,
					is_remove,
					is_commission,
					province_id,
					city_id,
					region_id,
					key: '',
					jiesuan_time: '',
					gushudi_key: '',
					gushudi_name: '',
					shouhuo_key: '',
					recharge_requirement: '',
					is_selection: '',
					age_min: '',
					age_max: '',
					sort: '',
					category_id: this.goodscategory[this.catecurrent]?.id || ''
				};
				console.log("this.searchform:::::",this.searchform);
				this.searchform.page = 1;
				setTimeout(() => {
					this.refreshGoodsList();
				}, 100);
				this.bigsearch = false;
			},

			// 刷新商品列表
			refreshGoodsList() {
				if (this.$refs.user_goods && this.$refs.user_goods.goodsList) {
					this.$refs.user_goods.goodsList(this.searchform);
				} else {
					setTimeout(() => {
						this.refreshGoodsList();
					}, 100);
				}
			},

			// 获取用户位置
			selfLocation() {
				this.$util.$L.getLocation().then(res => {
					const param = {
						lng: res.longitude,
						lat: res.latitude,
						version: 1
					}
					this.$httpApi.commonInit(param).then(res => {
						// 位置信息赋值
						let addarr = res.data.citydata.mergename.split(',');
						console.log(addarr);
						this.addressInfo.province = addarr[1];
						this.addressInfo.province_id = res.data.citydata.province_id;
						this.addressInfo.area = addarr[2];
						this.addressInfo.area_id = res.data.citydata.area_id;
						this.addressInfo.region = addarr[3];
						this.addressInfo.region_id = res.data.citydata.region_id;
						
						this.searchform.province_id = res.data.citydata.province_id;
						this.searchform.city_id = res.data.citydata.area_id;
						this.searchform.region_id = res.data.citydata.region_id;
						
						// 获取完定位后查询商品信息
						this.$refs.user_goods.goodsList(this.searchform); // 商品列表
					})
				})
			},

			// 获取轮播图
			async getBanners() {
				try {
					const res = await this.$httpApi.indexBanner();
					this.bannerList = res.data || [];
				} catch (error) {
					console.error('获取轮播图失败:', error);
					this.bannerList = [];
				}
			},

			// 首页弹窗信息
			async popDictionary() {
				try {
					const res = await this.$httpApi.popDictionary();
					console.log("首页弹窗信息：", res);
				} catch (error) {
					console.error('获取弹窗信息失败:', error);
				}
			},

			// 滚动通知
			async systemContent() {
				try {
					const res = await this.$httpApi.systemContent();
					this.systemContentdata = res.data || { title: '', content: '' };
				} catch (error) {
					console.error('获取系统内容失败:', error);
					this.systemContentdata = { title: '', content: '' };
				}
			},

			// 商品分类
			async getCateList() {
				try {
					const res = await this.$httpApi.getCateList();
					this.goodscategory = res.data || [];
					// 添加全部商品选项
					if (this.goodscategory.length > 0) {
						this.goodscategory.unshift({ name: '全部商品', id: '' });
					}
				} catch (error) {
					console.error('获取分类失败:', error);
					this.goodscategory = [{ name: '全部商品', id: '' }];
				}
			},

			// 切换分类
			cateChange(item) {
				const index = this.goodscategory.findIndex(cate => cate.name === item.name);
				if (index > -1) {
					this.catecurrent = index;
				}
				
				this.searchform.page = 1;
				this.searchform.category_id = item.id || '';
				this.searchform.key = ''; // 清空关键词搜索
				this.refreshGoodsList();
			},
			// 首充金额选择
			selectRecharge(value) {
				this.searchform.recharge_requirement = value;
			},

			// 打开地区选择
			openAreaSelect() {
				if (this.$refs.cityPickerRef) {
					this.$refs.cityPickerRef.open();
				}
			},

			// 处理地区选择结果
			handleConfirm(res) {
				if (res && res.province && res.city && res.district) {
					this.addressInfo = {
						province: res.province.name,
						province_id: res.province.id,
						area: res.city.name,
						area_id: res.city.id,
						region: res.district.name,
						region_id: res.district.id,
					};
					
					this.searchform.province_id = res.province.id;
					this.searchform.city_id = res.city.id;
					this.searchform.region_id = res.district.id;
					
					this.refreshGoodsList();
				}
			},

			// 轮播图点击
			bannerBtn(index) {
				if (this.bannerList[index] && this.bannerList[index].id) {
					uni.navigateTo({
						url: '/pages/shop/banner_details?id=' + this.bannerList[index].id
					});
				}
			},

			// 跳转页面
			goPath(url) {
				if (url) {
					uni.navigateTo({
						url: url
					});
				}
			},

			// 复制文本
			copyBtn(txt) {
				if (txt) {
					uni.setClipboardData({
						data: txt.toString(),
						success: () => {
							this.$tips.toast('复制成功');
						},
						fail: () => {
							this.$tips.toast('复制失败');
						}
					});
				}
			},

			// 店铺信息
			async shopInfo() {
				try {
					this.$tips.showLoading('加载中');
					const res = await this.$httpApi.userShopInfo();
					if (res.code == 1) {
						console.log("店铺信息：", res);
						// 可以在这里更新storeinfo
					}
				} catch (error) {
					console.error('获取店铺信息失败:', error);
				} finally {
					this.$tips.hideLoading();
				}
			},

			// 产品筛选条件
			async productSearch() {
				try {
					this.$tips.showLoading('加载中');
					const res = await this.$httpApi.productSearch();
					if (res.code == 1) {
						this.pdsearchdata = res.data || {};
						if (this.pdsearchdata.recharge_requirement_arr) {
							this.rechargeOptions = this.convertObjToOptions(this.pdsearchdata.recharge_requirement_arr);
						}
					}
				} catch (error) {
					console.error('获取筛选条件失败:', error);
					this.pdsearchdata = {};
				} finally {
					this.$tips.hideLoading();
				}
			},
			// 跳转商品详情
			todetail(id) {
				if (id) {
					const agid = this.userinfo?.id || '';
					uni.navigateTo({
						url: `/pages/mall/details_first?id=${id}&agid=${agid}`
					});
				}
			},

			// 生成海报
			createBanner() {
				let item = {};
				item.id=1;
				item.packages_id = 1;
				if (item && item.id && item.packages_id) {
					uni.navigateTo({
						url: `/pages/order/CreateBanner?id=${item.id}&packages_id=${item.packages_id}`
					});
				}
			},
		}
	}
</script>

<style lang="less">
	.order {
		width: 100%;
		min-width: 100%;
		background: #f5f5f5;
		color: #333;
		box-sizing: border-box;
		min-height: 100vh;
		padding-bottom: 100rpx;

		// 轮播
		.banner-list {
			position: relative;
			margin-bottom: -60rpx;
			z-index: 0;
		}
		
		// 优化图片加载
		image {
			will-change: transform;
		}
		
		// 列表优化
		.pdlist {
			contain: layout style paint;
		}
	}
</style>